<template>
  <view class="preview-container">
    <view class="card-preview" :style="cardBgStyle">
      <text class="card-text">{{ inputText || '请输入要生成的文字' }}</text>
    </view>
    <!-- 隐藏canvas用于合成图片 -->
    <canvas canvas-id="cardCanvas" class="hidden-canvas" style="width:600px;height:600px;position:absolute;left:-9999px;top:-9999px;" />
    <view class="template-list">
      <view v-for="(tpl, idx) in templates" :key="idx" :class="['template-item', selectedTemplate === idx ? 'selected' : '']" @click="selectTemplate(idx)">
        <image :src="tpl.thumb" class="template-thumb" />
        <text class="template-name">{{ tpl.name }}</text>
      </view>
    </view>
    <button class="next-btn" type="primary" @click="handleNext">下一步</button>
  </view>
</template>

<script>
import { generateImage } from '@/api/task'
export default {
  data() {
    return {
      inputText: '',
      templates: [
        { name: '基础', value: 'basic', thumb: '/static/images/template-basic.png', bg: '#c8f4f7', bgImg: '/static/images/template-basic.png' },
        { name: '边框', value: 'border', thumb: '/static/images/template-border.png', bg: '#f4f4f4', bgImg: '/static/images/template-border.png' },
        { name: '备忘', value: 'note', thumb: '/static/images/template-note.png', bg: '#fffbe6', bgImg: '/static/images/template-note.png' },
        { name: '手写', value: 'handwrite', thumb: '/static/images/template-handwrite.png', bg: '#fdf6ec', bgImg: '/static/images/template-handwrite.png' },
        { name: '光影', value: 'shadow', thumb: '/static/images/template-shadow.png', bg: '#f5f7fa', bgImg: '/static/images/template-shadow.png' }
      ],
      selectedTemplate: 0
    }
  },
  computed: {
    cardBgStyle() {
      const tpl = this.templates[this.selectedTemplate];
      if (tpl.bgImg) {
        return {
          background: `${tpl.bg ? tpl.bg : '#fff'} url(${tpl.bgImg}) center center / 100% 100% no-repeat`
        }
      }
      return { background: tpl.bg }
    }
  },
  methods: {
    selectTemplate(idx) {
      this.selectedTemplate = idx;
    },
    async handleNext() {
      if (!this.inputText) {
        uni.showToast({ title: '请输入文字', icon: 'none' });
        return;
      }
      uni.showLoading({ title: '图片生成中...' });
      // 1. 先下载背景图片到本地
      const bgImgUrl = this.templates[this.selectedTemplate].bgImg;
      let localBgPath = bgImgUrl;
      try {
        if (!bgImgUrl.startsWith('http')) {
          // 本地图片需用uni.getImageInfo获取本地路径
          const info = await new Promise((resolve, reject) => {
            uni.getImageInfo({ src: bgImgUrl, success: resolve, fail: reject })
          });
          localBgPath = info.path;
        }
      } catch (e) {
        uni.hideLoading();
        uni.showToast({ title: '图片加载失败', icon: 'none' });
        return;
      }
      // 2. 绘制canvas
      const ctx = uni.createCanvasContext('cardCanvas', this);
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, 600, 600);
      ctx.drawImage(localBgPath, 0, 0, 600, 600);
      // 3. 绘制文字（多行居中）
      ctx.setFillStyle('#444');
      ctx.setFontSize(36);
      ctx.setTextAlign('center');
      ctx.setTextBaseline('middle');
      const lines = this.inputText.split('\n');
      const lineHeight = 56;
      const startY = 300 - (lines.length - 1) * lineHeight / 2;
      lines.forEach((line, i) => {
        ctx.fillText(line, 300, startY + i * lineHeight);
      });
      ctx.draw(false, () => {
        // 4. 导出图片
        uni.canvasToTempFilePath({
          canvasId: 'cardCanvas',
          width: 600,
          height: 600,
          destWidth: 600,
          destHeight: 600,
          success: (res) => {
            uni.hideLoading();
            const imagePath = res.tempFilePath;
            uni.navigateTo({
              url: '/pages/tabbar/publish/publish?imagePath=' + encodeURIComponent(imagePath)
            });
          },
          fail: (err) => {
            uni.hideLoading();
            uni.showToast({ title: '图片生成失败', icon: 'none' });
          }
        }, this);
      });
    }
  },
  onLoad(options) {
    if (options.text) {
      this.inputText = decodeURIComponent(options.text)
    }
  }
}
</script>

<style scoped>
.preview-container {
  padding: 32rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.card-preview {
  width: 90vw;
  height: 60vh;
  border-radius: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.06);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32rpx;
  margin-top: 24rpx;
}
.card-text {
  font-size: 48rpx;
  color: #444;
  text-align: center;
  word-break: break-all;
  white-space: pre-line;
  width: 80vw;
  min-height: 100rpx;
}
.hidden-canvas {
  position: absolute;
  left: -9999px;
  top: -9999px;
  width: 600px;
  height: 600px;
}
.template-list {
  display: flex;
  flex-direction: row;
  margin-bottom: 32rpx;
}
.template-item {
  margin-right: 24rpx;
  border: 2rpx solid #eee;
  border-radius: 12rpx;
  padding: 8rpx 12rpx;
  text-align: center;
}
.template-item.selected {
  border-color: #007aff;
}
.template-thumb {
  width: 80rpx;
  height: 100rpx;
  margin-bottom: 8rpx;
}
.template-name {
  font-size: 24rpx;
}
.next-btn {
  width: 60vw;
  background: #ff3b30;
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
  padding: 16rpx 0;
  margin-top: 24rpx;
  margin-bottom: 32rpx;
  display: block;
}
</style> 